package xin.marcher.module.replenished.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.inventory.domain.response.WarningInventoryDTO;
import xin.marcher.module.replenished.remote.InventoryRemote;
import xin.marcher.module.replenished.service.WarningInventoryService;

import javax.annotation.Resource;
import java.util.List;

/**
 * 处理 库存预警的消息消费
 */
@Slf4j
@Component
public class WarningInventoryListener implements MessageListenerConcurrently {

    @Resource
    private WarningInventoryService warningInventoryService;

    @Resource
    private InventoryRemote inventoryRemote;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("执行库存预警，消息内容：{}", msg);

                WarningInventoryDTO warningInventoryDTO = JsonUtil.json2Object(msg, WarningInventoryDTO.class);
                //1. 入预警缓存
                JsonResult jsonResult = warningInventoryService.warningInventory(warningInventoryDTO);
                //2. 通知库存消息预警，只有有效的才通知
                if (jsonResult.getSuccess()) {
                    inventoryRemote.warningInventoryMessage(warningInventoryDTO);
                }
            }
        } catch (Exception e) {
            log.error("consume error, 库存预警失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
